package com.thinkit.security.custom;

import com.google.common.collect.Sets;
import com.thinkit.cms.api.admin.PermissionService;
import com.thinkit.core.base.BaseContextKit;
import com.thinkit.core.constant.SecurityConstants;
import com.thinkit.utils.properties.PermitAllUrlProperties;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Set;
public class CustomAuthPermsSource {

    @Autowired
    PermitAllUrlProperties permitAllUrlProperties;

    @Autowired
    PermissionService permissionService;

    protected RequestMatcher requestMatcher;

   protected Collection<ConfigAttribute> queryPermByUrl(String url){
       String clientId=BaseContextKit.getUserClient();
       Collection<ConfigAttribute> atts = Sets.newHashSet();
       String perm= permissionService.selectPermIdsByUrl(url,clientId);
       if(Checker.BeBlank(perm)){
           if(permitAllUrlProperties.getStrict()){ // 严格模式,没配置不允许访问 or 没配置可以访问
               perm = "fail-it-can't-be-repeated";
           }else{
               perm = SecurityConstants.AUTHC;
           }
       }
       atts.add(new SecurityConfig(perm));
       return atts;
   }


   protected Set<String> queryPermsByUid(){
       String userId = BaseContextKit.getUserId(),
       clientId=BaseContextKit.getUserClient();
       Set<String> perms =permissionService.selectPermsByUid(userId,clientId);
       perms.add(SecurityConstants.AUTHC);
       if(Checker.BeNotEmpty(perms)){
           perms.addAll(perms);
       }
       return perms;
   }

   protected boolean isAuthcUrl(HttpServletRequest request){
       return requestMatcher.matches(request);
   }

   protected  Collection<ConfigAttribute> returnAuthcUrl(){
       Collection<ConfigAttribute> atts = Sets.newHashSet();
       atts.add(new SecurityConfig(SecurityConstants.AUTHC));
       return atts;
   }


}
